﻿using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Text;

public enum LogKind
{
	Error = 0,
	Assert = 1,
	Warning = 2,
	Log = 3,
	Exception = 4,
	User = 5,
	Debug = 6
}

public static class Log
{
	public static int consoleMaxLines = 32;
	public static bool writeToConsole = false;
	public static List<string> consoleLines = new List<string>();

	public static string consoleText { get { return string.Join( "\n", consoleLines.ToArray() ); } }

	private static StreamWriter log = null;

	private static void InitLogFile()
	{
		string filename = Application.isEditor ? "logfile_editor.txt" : "logfile.txt";
		log = new StreamWriter( filename, false, Encoding.UTF8 );
	}

	public static void Write( string text, LogKind kind = LogKind.User )
	{
		if ( log == null )
			InitLogFile();

		log.Write( text );
		log.Flush();

		if ( writeToConsole )
			WriteToConsole( text, kind );
	}

	public static void WriteLine( string text, LogKind kind = LogKind.User )
	{
		if ( log == null )
			InitLogFile();

		log.WriteLine( text );
		log.Flush();

		if ( writeToConsole )
			WriteToConsole( text, kind );
	}

	public static void WriteToConsole( string text, LogKind kind = LogKind.User )
	{
		text.TrimEnd( '\n', '\r' );

		if ( kind != LogKind.Log && kind != LogKind.User )
			text = "[" + kind + "] " + text;

		if ( text != "" )
		{
			string color;
			switch ( kind )
			{
				case LogKind.Warning:
					color = "#FFFF33FF";
					break;

				case LogKind.Log:
					color = "#33FF33FF";
					break;

				case LogKind.User:
					color = "#FFFFFFFF";
					break;

				default:
					color = "#FF3333FF";
					break;
			}
			text = "<color=" + color + ">" + text + "</color>";
		}

		consoleLines.Add( text );
		if ( consoleLines.Count > consoleMaxLines )
			consoleLines.RemoveAt( 0 );

		//consoleText += text;
		//while ( consoleText.Length > consoleMaxLength )
		//{
		//	int nIndex = consoleText.IndexOf( '\n' );
		//	consoleText = consoleText.Substring( nIndex + 1 );
		//}
	}

	public static void Close()
	{
		if ( log != null )
		{
			log.Close();
			log = null;
		}
	}
}